/****************************************************************************
 *  Sample client program to test the following XP functions:
 *     XPmul()
 *     XPadd()
 *     XPsub()
 *     XPinitDecimal()
 *     XPless()
 *     XPrand()
 *
 *  Compilation:  gcc126 testadd.c xp.c
 *  Execution:    a.out
 *
 *  If anything is printed, you probably have a bug.
 *
 ****************************************************************************/


#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "XP.h"

#define TRIALS 500

/***********************************************
 * check identity (a-b)^2 = a^2 + b^2 -2ab
 ***********************************************/
int test_mul(XP a, XP b) {
  XP aa = XPmul(a, a);
  XP bb = XPmul(b, b);
  XP ab = XPmul(a, b);
  XP d = XPmul(XPsub(a,b), XPsub(a,b));
  XP e = XPsub(XPsub(XPadd(aa, bb), ab), ab);

  if(!XPeq(d, e)) {
      printf("Error detected while running testmul.c\n");
      printf("a           = "); XPshowDecimal(a); printf("\n");
      printf("b           = "); XPshowDecimal(b); printf("\n");
      printf("(a-b)^2     = "); XPshowDecimal(d); printf("\n");
      printf("a^2+b^2-2ab = "); XPshowDecimal(e); printf("\n");
      printf("\n");
      return 1;
   }

   return 0;
}


/************************************************************
 *  Sample client to help test multiply.
 *  Assumes XPless(), XPsub(), XPadd(), and XPrand() are OK
 ************************************************************/
bool test_mul(void) {
   bool result = true;
   int i;
   XP a, b, t;

   srand((unsigned int) time(NULL));

   // test on some small integers
   a = XPinitDecimal("46460");
   b = XPinitDecimal("551");
   test_mul(a, b);

   a = XPinitDecimal("999989");
   b = XPinitDecimal("0");
   test_mul(a, b);

   for (i = 0; i < TRIALS; i++) {
      a = XPrand(N);
      b = XPrand(N);
      if (XPless(a,b))     // make sure a >= b
         t = a, a = b, b = t;
      if (test_mul(a, b)) { result = false; break; }
   }

   return result;
}

